<?php
namespace app\api\middleware;

use app\common\base\Errors;
use think\Request;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use app\common\exception\BaseException;
use app\common\logic\AuthLogic;

class CheckJwtToken
{
    public function handle(Request $request, \Closure $next)
    {
        //获取 token
	    $Logic = new AuthLogic();
        $token = $Logic->getToken();
        if(!$token && PHP_OS == 'WINNT') {
	        $token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1NDQ0OTg0NjEsImlkIjoyfQ.AEICrsBp3mjYoZVcOU15yxpBdnQd2IJ1eRThou5nMsI';
        }
        if($token == ''){ throw new BaseException(1031, Errors::$codes[1031]); }

        //验证 token
        $parse = (new Parser())->parse($token);
        $ok = $parse->verify((new Sha256()), config('jwt_secret'));
        if( ! $ok){ throw new BaseException(1033, Errors::$codes[1033]); }
        $id = $parse->getClaim('id');
        $id = intval($id);
        if($id < 1){ throw new BaseException(1033, Errors::$codes[1033]); }
        //定义 ADMIN_ID
        define('ADMIN_ID', $id);
        //下一步
        return $next($request);
    }
}
